/*
 * @FilePath: /fxfzywpt/src/map/ArcgisService.js
 * @Description:
 */

import '@/assets/map/ol/ol.css';
import {
  getProjection,
  getResolutions,
  getTiandituVecMap,
  getTiandituVecText,
  getTiandituImgMap,
  getTiandituImgText,
  getRESTLayer,
  getVectorTileLayer,
  iServerHttp,
  meterToDegree,
} from '@/map/projMap.js';
import Map from 'ol/Map';
import View from 'ol/View';
import VectorLayer from 'ol/layer/Vector';
import { Vector as VectorSource } from 'ol/source';
import { Control } from 'ol/control';
// import ScaleLine from 'ol/control/ScaleLine';
import WKT from 'ol/format/WKT';
import GeoJSON from 'ol/format/GeoJSON';
import Overlay from 'ol/Overlay';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import Circle from 'ol/geom/Circle';
import { fromCircle } from 'ol/geom/Polygon';
import { Fill, Stroke, Style, Icon, Circle as CircleStyle, Text } from 'ol/style';
import { Select, Draw, Modify, Snap, Translate } from 'ol/interaction';
import { getArea, getLength } from 'ol/sphere';
import { unByKey } from 'ol/Observable';
import { boundingExtent } from 'ol/extent';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import { MapService, GetFeaturesByGeometryParameters, FeatureService } from '@supermap/iclient-ol';
import { ElLoading } from 'element-plus';
import { transform } from 'ol/proj';
export class ArcgisService {
  // ArcGISurl:"http://10.19.41.41:6080/arcgis/rest/services",//活断层服务地址
  constructor(options) {
    console.log('--options--', options);
    if (options.map) {
      ArcgisService.setMap(options.map);
    }
    if (options.maskLayer) {
      ArcgisService.setMaskLayer(options.maskLayer);
    }
    var token = getDefaultToken();
    if (options.ArcGIStoken) {
      token = options.ArcGIStoken;
    }
    ArcgisService.setToken(token);
    var color1 = getDefaultColor1();
    var color2 = getDefaultColor2();
    var color3 = getDefaultColor3();
    var color4 = getDefaultColor4();
    if (options.holoceneColor) {
      color1 = options.holoceneColor;
    }
    ArcgisService.setHoloceneColor(color1);
    if (options.latePleistoceneColor) {
      color2 = options.latePleistoceneColor;
    }
    ArcgisService.setLatePleistoceneColor(color2);
    if (options.earlyMiddlePleistoceneColor) {
      color3 = options.earlyMiddlePleistoceneColor;
    }
    ArcgisService.setEarlyMiddlePleistoceneColor(color3);
    if (options.prequaternaryColor) {
      color4 = options.prequaternaryColor;
    }
    ArcgisService.setPrequaternaryColor(color4);
    function getDefaultToken() {
      let token =
        process.env.NODE_ENV === 'development'
          ? 'Ro6cnm4oW6dPfe0YkJVzsl_SnLcHi8obuK9gxo8eaKzfyD2QWPBPOSqrUUXwyqt_KWU6D99WVLHRH9WuJoc_ww..'
          : 'ZquJDoUHIUnDFsnsd_MhNqudzSH9ikjzezBubXFMk5Ezf75z3AnNyFlVo7z8EHtm4C0C4zYso08C5bFaQl4GWw..';
      return token;
    }
    function getDefaultColor1() {
      return 'rgba(255,37,37,1)';
    }
    function getDefaultColor2() {
      return 'rgba(227,46,255,1)';
    }
    function getDefaultColor3() {
      return 'rgba(37,255,130,1)';
    }
    function getDefaultColor4() {
      return 'rgba(253,190,65,1)';
    }
  }
  static getArcgisUrl() {
    // http://10.19.41.41:6080/arcgis/rest/services/全国断层服务器发布图层/MapServer/
    return import.meta.env.VITE_APP_ARCGIS_URL;
  }
  /**
   * 设置map
   * @param {*} map
   */
  static setMap(map) {
    this.map = map;
  }
  static getMap() {
    return this.map;
  }
  static setMaskFeature(maskFeature) {
    this.maskFeature = maskFeature;
  }
  // 全国范围的feature
  static getMaskLFeature() {
    return this.maskFeature;
  }
  static setToken(ArcGIStoken) {
    this.ArcGIStoken = ArcGIStoken;
  }
  static getToken() {
    return this.ArcGIStoken;
  }

  static setHoloceneColor(color) {
    this.HoloceneColor = color;
  }
  static getHoloceneColor() {
    // return 'rgba(255,37,37,1)';
    return this.HoloceneColor;
  }
  static setLatePleistoceneColor(color) {
    this.LatePleistoceneColor = color;
  }
  static getLatePleistoceneColor() {
    // return 'gba(227,46,255,1)';
    return this.LatePleistoceneColor;
  }
  static setEarlyMiddlePleistoceneColor(color) {
    this.EarlyMiddlePleistoceneColor = color;
  }
  static getEarlyMiddlePleistoceneColor() {
    // return 'rgba(37,255,130,1)';
    return this.EarlyMiddlePleistoceneColor;
  }
  static setPrequaternaryColor(color) {
    this.PrequaternaryColor = color;
  }
  static getPrequaternaryColor() {
    // return 'gba(253,190,65,1)';
    return this.PrequaternaryColor;
  }
  async getFeatureDataByFid(fid) {
    return new Promise((resolve, reject) => {
      let token = ArcgisService.getToken();
      let url = encodeURI(
        `${ArcgisService.getArcgisUrl()}/arcgis/rest/services/全国断层服务器发布图层/MapServer/0/query?f=json&objectIds=${fid}&outFields=断层倾向,断层名称,断层性质,断层走向,断层长度,活动时代,FID&outSR=102100&returnM=true&returnZ=true&spatialRel=esriSpatialRelIntersects&where=1=1&token=${token}`
      );
      //图层图例信息查询
      let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
      httpRequest.open('GET', url, true); //第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
      /**
       * 获取数据后的处理程序
       */
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText; //获取到json字符串，还需解析
          let obj = JSON.parse(json);
          console.log('obj---', obj);
          let features = obj.features;
          let attributes = features[0].attributes;
          resolve(attributes);
        }
      };
    });
  }
  async showArcgisHddcLayerByName(arrSqlFilter, { key, value }) {
    if (arrSqlFilter && arrSqlFilter.length > 0) {
      let layer = new VectorLayer({
        source: new VectorSource({
          wrapX: false,
        }),
        projection: 'EPSG:4490',
        zIndex: 20,
      });
      layer.set(key, value);
      let layerMap = new Map();
      for (let index = 0; index < arrSqlFilter.length; index++) {
        let sqlFilter = arrSqlFilter[index];
        let xMin = 60;
        let xMax = xMin + 6;
        let yMin = 0;
        let yMax = 60;
        for (let i = 0; i < 20; i++) {
          //转换为3857坐标
          let minLonLat = ArcgisService.getTransformLonLat3857([xMin, yMin]);
          let maxLonLat = ArcgisService.getTransformLonLat3857([xMax, yMax]);
          //根据范围查询Arcgis服务活动断层
          let featureTmps = await ArcgisService.showArcgisHddcLayerByBound(
            sqlFilter,
            minLonLat[0],
            maxLonLat[0],
            minLonLat[1],
            maxLonLat[1]
          );
          xMin = xMax;
          xMax = xMax + 6;
          featureTmps.forEach((feature) => {
            layer.getSource().addFeature(feature);
          });
        }
      }
      layerMap.set(key, layer);
      return new Promise((resolve) => {
        resolve(layerMap);
      });
    }
  }
  async showArcgisHddcLayer(sqlFilter) {
    let layerMap = new Map();
    let xMin = 60;
    let xMax = xMin + 6;
    let yMin = 0;
    let yMax = 60;
    let layer = new VectorLayer({
      source: new VectorSource({
        wrapX: false,
      }),
      projection: 'EPSG:4490',
      zIndex: 20,
    });
    layer.set('arcName', sqlFilter);
    for (let i = 0; i < 20; i++) {
      //转换为3857坐标
      let minLonLat = ArcgisService.getTransformLonLat3857([xMin, yMin]);
      let maxLonLat = ArcgisService.getTransformLonLat3857([xMax, yMax]);
      //根据范围查询Arcgis服务活动断层
      let featureTmps = await ArcgisService.showArcgisHddcLayerByBound(
        sqlFilter,
        minLonLat[0],
        maxLonLat[0],
        minLonLat[1],
        maxLonLat[1]
      );
      xMin = xMax;
      xMax = xMax + 6;
      featureTmps.forEach((feature) => {
        layer.getSource().addFeature(feature);
      });
    }
    console.log('keyvalue---', layer.getSource().getFeatures());
    layerMap.set(sqlFilter, layer);
    return new Promise((resolve) => {
      resolve(layerMap);
    });
    // resolve({ key: sqlFilter, layer: layer });
  }
  /**
   * 根据范围查询Arcgis服务活动断层
   * @param {*} sqlFilter 查询条件
   * @param {*} xMin
   * @param {*} xMax
   * @param {*} yMin
   * @param {*} yMax
   */
  static showArcgisHddcLayerByBound(sqlFilter, xMin, xMax, yMin, yMax) {
    let that = this;
    return new Promise(function (resolve, reject) {
      let token = that.getToken();
      let color1 = that.getHoloceneColor();
      let color2 = that.getLatePleistoceneColor();
      let color3 = that.getEarlyMiddlePleistoceneColor();
      let color4 = that.getPrequaternaryColor();
      let featureTmps = [];
      let url = encodeURI(
        `${that.getArcgisUrl()}/arcgis/rest/services/全国断层服务器发布图层/MapServer/0/query?f=json&geometry={"spatialReference":{"latestWkid":3857,"wkid":102100},"xmin":${xMin},"ymin":${yMin},"xmax":${xMax},"ymax":${yMax}}&maxAllowableOffset=9783.939620500008&maxRecordCountFactor=3&outFields=FID,活动时代&outSR=102100&resultType=tile&returnExceededLimitFeatures=false&spatialRel=esriSpatialRelIntersects&where=(活动时代 like '%${sqlFilter}%')&geometryType=esriGeometryEnvelope&inSR=102100&token=${token}`
      );
      //图层图例信息查询
      let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
      httpRequest.open('GET', url, true); //第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
      /**
       * 获取数据后的处理程序
       */
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText; //获取到json字符串，还需解析
          let obj = JSON.parse(json);
          // console.log('obj---', obj);
          let features = obj.features;
          for (let i = 0; i < features.length; i++) {
            let FID = features[i].attributes.FID;
            let paths = features[i].geometry.paths[0];
            let lonlatArr = [];
            for (let j = 0; j < paths.length; j++) {
              let lonlat = that.getTransformLonLat4326(paths[j]);
              if (lonlat) {
                lonlatArr.push(lonlat);
              }
            }
            let featureTmp = new Feature({
              geometry: new LineString(lonlatArr),
            });
            featureTmp.set('FID', FID);
            if (sqlFilter == '全新世断层') {
              //样式
              let style = that.getLineStringStyle(color1);
              featureTmp.setStyle(style);
              // layer.getSource().addFeature(featureTmp);
            } else if (sqlFilter == '晚更新世断层') {
              //样式
              let style = that.getLineStringStyle(color2);
              featureTmp.setStyle(style);
              // layer.getSource().addFeature(featureTmp);
            } else if (sqlFilter == '早中更新世断层') {
              //样式
              let style = that.getLineStringStyle(color3);
              featureTmp.setStyle(style);
              // layer.getSource().addFeature(featureTmp);
            } else if (sqlFilter == '前第四纪断层') {
              //样式
              let style = that.getLineStringStyle(color4);
              featureTmp.setStyle(style);
              // layer.getSource().addFeature(featureTmp);
            }
            // layer.getSource().addFeature(featureTmp);
            featureTmps.push(featureTmp);
          }
          console.log('featuretmps');
          resolve(featureTmps);
        }
      };
    });
  }

  static getTransformLonLat4326(lonlat) {
    //转换为4326坐标
    let resultLonLat = null;
    if (lonlat != null && lonlat.length == 2) {
      let sourceProj = 'EPSG:3857'; // 原始坐标系为墨卡托投影
      let destProj = 'EPSG:4326'; // 目标坐标系为经纬度
      resultLonLat = transform(lonlat, sourceProj, destProj); //坐标转换
    }
    return resultLonLat;
  }

  static getTransformLonLat3857(lonlat) {
    // 实现 getTransformLonLat3857 的逻辑
    //转换为3857坐标
    let resultLonLat = null;
    if (lonlat != null && lonlat.length == 2) {
      let sourceProj = 'EPSG:4326'; // 原始坐标系为经纬度
      let destProj = 'EPSG:3857'; // 目标坐标系为墨卡托投影
      resultLonLat = transform(lonlat, sourceProj, destProj); //坐标转换
    }
    return resultLonLat;
  }
  static getLineStringStyle(color) {
    //线样式
    let style = new Style({
      fill: new Fill({
        //填充样式
        color: color,
      }),
      stroke: new Stroke({
        //线
        width: 2, //宽
        color: color,
      }),
    });

    return style;
  }
}
